package ar.com.photo_admin.jobs

import javax.annotation.PostConstruct;

import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.springframework.context.ApplicationContext;

import ar.com.photo_admin.service.*;
import ar.com.photo_admin.domain.*;

class PublishPhotosJob extends BaseService{
	
	def GCSEnabled;	
	def commandTool;
	def bucketUrl;
	def curlCommandTool;
	def finishUploadUrl;
	def photosHostedUrl;
	def hostedInWindows;
	def windowsConsolePrefix;
	
	def remoteFileHostingService;
	
	@PostConstruct
	def initJob(){
		GCSEnabled = grailsApplication.config.gcs.appplication.enabled
		bucketUrl = grailsApplication.config.gcs.appplication.bucketUrl
		commandTool = grailsApplication.config.gcs.config.commandTool
		curlCommandTool = grailsApplication.config.curl.config.installedPath
		finishUploadUrl = grailsApplication.config.gcs.appplication.finishUploadUrl
		photosHostedUrl = grailsApplication.config.gcs.commons.photosHostedUrl 
		hostedInWindows = grailsApplication.config.hostedInWindows
		windowsConsolePrefix = grailsApplication.config.windowsConsolePrefix
	}
	
    static triggers = {
      simple name: 'publishPhotosTrigger', startDelay: 20*60*1000, repeatInterval: 60*60*1000  
    }

    def execute() {				
		
        log.info "Ha comenzado el proceso para subir fotos a GCS"
		
		if (!GCSEnabled){
			log.info "La publicación de fotos se encuentra desactivada"
			return;
		}
				
		//Busco los eventos que todavia no fueron publicados.		
		def nonPublishedEvents = Event.findAllByPublished(false);
		
		nonPublishedEvents.each { event ->
			event = event.refresh()				
			log.info "Subiendo las fotos del evento numero ${event.number}"
			
			//Subo cada foto que no este publicada
			event.photos.each { photo ->
				if (!photo.hosted){
					
					String[] urls = [ photo.pathInServer, photo.thumbnailMediumPathInServer, photo.thumbnailPathInServer ]
					
					//Sube la foto y los thumbnails
					urls.each { url ->
						String uploadCommand = "${ hostedInWindows ? windowsConsolePrefix : ''} ${commandTool} cp -a public-read -R ${url} ${bucketUrl+event.number}/"
						
						def sout = new StringBuffer()
						def serr = new StringBuffer()
						
						log.info "Ejecutando comando a GCS: " +uploadCommand
						Process uploadProcess = uploadCommand.execute()
						uploadProcess.consumeProcessOutput(sout,serr)
						uploadProcess.waitFor()
						
						
					}													
					
				}
				
			}
			
			
			
			log.info "Ha finalizado la subida de fotos del evento numero ${event.number}"									
			
			remoteFileHostingService.registerUploadToHosting(event.id)								
		}
		
		log.info "Ha finalizado la ejecución del proceso para subir fotos a GCS"
    }
	

}
